import React, { PureComponent } from 'react'
import { connect } from 'dva';
import Link from 'umi/link';
import { Table, Divider, Modal, message, Popconfirm } from 'antd';
import Form from './components/SearchForm';
import { checkInit } from '@/utils/util';
import Ellipsis from '@/components/Ellipsis'
export interface IProps {
  dispatch?: Function,
  children?: React.ReactNode,
  loading: boolean,
  buttons?: Array<any>,
  cond?: {
    pageNum: string,
    pageSize: string
  },
  list: {
    data: Array<any>,
    dataCnt: number
  },
  match: object,
  loginInfo: {
    roleName: String,
  },
  newPwd: String,
}

interface IState {
  current: number,
  showResetBtn: boolean,
}

const confirm = Modal.confirm;
const ONE_PAGE_SIZE = 10;

@connect(({ person, loading, menu, user }) => ({
  list: person.list || {},
  newPwd: person.newPwd,
  loading: loading.effects['person/queryPage'],
  buttons: menu.buttons,
  loginInfo: user.details,
  cond: person.cond || {}
}))
class Person extends PureComponent<IProps, IState> {

  readonly state: IState = {
    current: 1,
    showResetBtn: false,
  }

  queryData = (offset = 1, size = ONE_PAGE_SIZE) => {
    const { dispatch } = this.props;

    dispatch({
      type: 'person/queryPage',
      payload: {
        pageNum: offset,
        pageSize: size,
      },
    });
  }

  initCurrent = () => {
    this.setState({
      current: 1
    })
  }

  componentDidMount() {
    const { dispatch } = this.props;
    checkInit() ? dispatch({ type: `person/initCond` }) : this.queryData();
  }

  operate = (id, status, ind) => {
    const { dispatch } = this.props;
    let _this = this;
    dispatch({
      type: 'person/lock',
      payload: { id, ind }
    }).then(() => {
      _this.queryData(_this.state.current);
    })
  }

  onShowSizeChange = (current, pageSize) => {
    const { dispatch, cond } = this.props;
    cond.pageSize = pageSize;
    dispatch({ type: `person/updateCond`, payload: cond }).then(() => {
      this.initCurrent()
    })
  }

  resetPassword = (id) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'person/resetOtherPwd',
      payload: { id }
    }).then(() => {
      const { newPwd } = this.props;
      newPwd && Modal.success({
          title: `临时密码: ${newPwd}`,
          content: '临时密码将于24小时内失效, 请尽快修改密码!',
        })
    })
  }
  remove = (id: string) => {
    const { dispatch } = this.props;
    this.setState({
      current: 1
    }, () => {
      dispatch({
        type: 'person/deletePerson',
        payload: id
      }).then(() => {
        this.queryData()
      })
    })
  }
  render() {
    const { list, buttons = [] } = this.props;
    const { data = [], dataCnt } = list;
    const btnList = {};
    buttons.forEach(item => {
      btnList[item.name] = item.name
    });

    const ans = data && Array.isArray(data) ? data.map((item, index) => ({
      key: index,
      id: item.id,
      ind: index + 1 < 10 ? `0${index + 1}` : index + 1,
      loginName: item.loginName,
      realName: item.realName,
      positionName: item.positionName ? item.positionName : ' ',
      status: item.status,
      idCardNo: item.userInfomation && item.userInfomation.idCardNo ,
      isDuty: item.userInfomation && (+item.userInfomation.isDuty === 0 ? '否 ' : '是'), 
      certificate: item.userInfomation && item.userInfomation.certificate,
      fireRoomNames: item.userInfomation &&
       Array.isArray(item.userInfomation.fireRoomNames)
        && <Ellipsis tooltip={true} lines={1}>{item.userInfomation.fireRoomNames.join('/')}</Ellipsis>,

      mobile: item.mobile ? item.mobile : ' ',
    })
    ) : []
    const pagination = {
      total: dataCnt,
      showTotal: total => `共 ${total} 条`,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      onShowSizeChange: this.onShowSizeChange,
      onChange: (current) => {
        this.setState({ current })
        this.queryData(current)
      },
    };
    const columns = [
     {
      title: '用户名',
      dataIndex: 'loginName',
    }, 
    {
      title: '真实姓名',
      dataIndex: 'realName',
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
    },
     {
      title: '身份证',
      dataIndex: 'idCardNo',
    },  
    {
      title: '岗位',
      dataIndex: 'positionName',
    },  
    {
      title: '是否为值班人员',
      dataIndex: 'isDuty'
    },    
    {
      title: '证书编号',
      dataIndex: 'certificate'
    },
    {
      title: '所属消控室',
      dataIndex: 'fireRoomNames'
    }, 
    {
      title: '操作', key: 'x', render: (record, text, index) => {
        return (
          <div style={{ display: 'flex' }}>
            {/*
              btnList['详情'] ? <>
                <Link to={`/data/person/${record.id}/details`}>详情</Link>
                <Divider type="vertical" />
              </> : null
            */}
            {
              btnList['编辑'] ? <>
                <Link to={`/data/person/${record.id}/update`}>编辑</Link>
                <Divider type="vertical" />
              </> : null
            }
            {
              <>
              <Link to={`/data/person/${record.id}/auth`}>角色配置</Link>
              <Divider type="vertical" />
              </> 
            }
            {
                <>
                  <a onClick={() => {
                    this.resetPassword(record.id)
                  }}>重置密码</a>
                  <Divider type="vertical" />
                </>
            }
            {
              btnList['删除'] ?
               <>
              <Popconfirm title="确定停用此用户吗?" onConfirm={() => { this.operate(record.id, record.status, index) }} 
              okText="确定" cancelText="取消"
              >
                <a>{record.status === 'lock' ? '启用' : '停用'}</a>
              </Popconfirm>
                <Divider type="vertical" />
              </> : null
            }
            {
            <>
             
              <Popconfirm title="请确认是否删除?" onConfirm={() => this.remove(record.id)} okText="确定" cancelText="取消">
                <a>删除</a>
              </Popconfirm>
            </>  
            }
           
          </div>
        )
      }
    }];
    return (
      <>
        <Form current={this.state.current} initCurrent={this.initCurrent} new={!!btnList['新增']} />
        <Table
          columns={[{
            title: '序号',
            dataIndex: 'ind',
          }, ...columns]}
          pagination={pagination}
          dataSource={ans}
          bordered
          loading={this.props.loading}
        />
      </>
    );
  }
}

export default Person;
